package com.code.semaphore;

import java.sql.SQLOutput;
import java.sql.Timestamp;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) {

        //抢车位例子,三个车位，六个车抢，谁抢到谁停，停留3秒钟
        Semaphore semaphore = new Semaphore(3);

        for(int i = 1; i <= 6; i++){
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"号车抢到了车位");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+"号车停留了3秒钟");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
    }



}
